import type { ExtractPropTypes } from 'vue'
import { buildProps, definePropType, keysOf } from '@/utils'
import { CHANGE_EVENT, UPDATE_MODEL_EVENT } from '@/consts'

interface Book {
  title: string
  author: string
  year: number
}

export type TableDataItem = Record<string, unknown>
type TableData = TableDataItem[]
type PagerConfig = {
  pageSize: number
}
type LoadConfig = {
  url: string
  method: 'get' | 'post' | 'put' | 'delete'
  formatRes: (res: unknown) => TableData
}

const TypeComponentsMap = {
  success: 'SuccessFilled',
  warning: 'WarningFilled',
  error: 'CircleCloseFilled',
  info: 'InfoFilled',
}

export const customTableProps = buildProps({
  lazy: {
    type: Boolean,
    default: false,
  },
  data: {
    type: definePropType<TableData>(Array),
  },
  loadConfig: {
    type: definePropType<LoadConfig>(Object),
  },
  pagerConfig: {
    type: definePropType<PagerConfig>(Object),
    default: () => ({ pageSize: 10 }),
  },
  type: {
    type: String,
    values: keysOf(TypeComponentsMap),
    default: 'info',
  },
  tabindex: {
    type: [String, Number],
    default: 0,
  },
  book: {
    type: definePropType<Book>(Object),
  },
})

export const customTableEmits = {
  [UPDATE_MODEL_EVENT]: (val: string | null) => isString(val) || isNil(val),
  [CHANGE_EVENT]: (val: string | null) => isString(val) || isNil(val),
  activeChange: (val: string | null) => isString(val) || isNil(val),
}

export type CustomTableProps = ExtractPropTypes<typeof customTableProps>
export type CustomTableEmits = typeof customTableEmits
